package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class CWDHandle implements Handle {
	FtpSession ftpSession;

	public CWDHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String dir=line.substring(line.indexOf(" "));
		if(dir==null||dir.trim().length()<=0){
			os.write(("550 Requested action not taken.\r\n").getBytes());
			os.flush();
			return;
		}
		dir=dir.trim();
		dir=PathConvert.shrink(dir);
		String currentDir;
		if(dir.startsWith("/")){
			currentDir=dir;
		}else {
			currentDir=ftpSession.currentDir+"/"+dir;
		}
		currentDir=PathConvert.shrink(currentDir);
		currentDir=PathConvert.serverPathFormat(currentDir);
		String path = PathConvert.toServerPath(ftpSession.getRootDir(), currentDir);
		File file = new File(path.trim());
		if(!file.exists()){
			os.write(("550 File unavailable.\r\n").getBytes());
			os.flush();
			return;
		}
		ftpSession.currentDir=currentDir;
		os.write(("250 Directory changed to "+ftpSession.currentDir+"\r\n").getBytes());
		os.flush();
	}
}
